package com.clothes.act;

import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.clothes.R;
import com.clothes.app.BaseUrl;
import com.clothes.http.JsonCallBack;
import com.clothes.mdoel.ClothesTable;
import com.clothes.mdoel.ServerInfo;
import com.clothes.utils.DateTool;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 交货
 */
public class SubmitProduct extends BaseActivity {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_time)
    TextView tvTime;
    @Bind(R.id.et_gh)
    EditText etGh;
    @Bind(R.id.tv_kh)
    TextView tvKh;
    @Bind(R.id.tv_color)
    TextView tvColor;
    @Bind(R.id.tv_size)
    TextView tvSize;
    @Bind(R.id.et_num)
    EditText etNum;
    @Bind(R.id.btn_submit)
    Button btnSubmit;
    @Bind(R.id.tv_name)
    TextView mTvName;

    private String uuid = "";
    private boolean isEdit;//工号输入后是否清空下面数据
    private int claim;//領了多少貨
    private int numType ; // 0 正常，1 超过，2 小于
    private int status = 2;// 超过 或者正常状态

    @Override
    public void initView() {
        setContentView(R.layout.activity_submit_product);
    }

    @Override
    public void initData() {
        tvTitle.setText("交货");
        setTime(5);
        tvTime.setText(DateTool.getStringDate(System.currentTimeMillis(),"yyyy-MM-dd HH:mm"));
        etGh.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(isEdit){
                    tvKh.setText("");
                    tvColor.setText("");
                    tvSize.setText("");
                    etNum.setText("");
                    isEdit = false;
                }
                //根据工号查询姓名
                String res = charSequence.toString();
                if(res.length() > 1){
                    getName(res);
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }

    @OnClick({R.id.iv_back, R.id.tv_time, R.id.tv_color, R.id.tv_size, R.id.btn_submit,R.id.tv_kh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.tv_time:
                timePickerView.show();
                break;
            case R.id.tv_kh:
                if(etGh.getText().toString().equals("")){
                    showToast("请先输入工号");
                    break;
                }
                getDataByKh(etGh.getText().toString().trim());
                break;
            case R.id.tv_color:
                if(tvKh.getText().toString().equals("")){
                    showToast("请先选择款号");
                    break;
                }
                break;
            case R.id.tv_size:
                if(tvKh.getText().toString().equals("")){
                    showToast("请先选择款号");
                    break;
                }
                break;
            case R.id.btn_submit:
                String N = etNum.getText().toString();
                if(parseInt(N) > claim){ //超过
                    numType = 1;
                    showDialog("大于可领数量("+claim+")件","我再想想","残忍提交");
                }else if(parseInt(N) < claim){
                    numType = 2;
                    showDialog("小于可领数量("+claim+")件","按全部交货","按当前交货");
                }else {
                    numType = 0;
                    submit();
                }
                break;
        }
    }

    @Override
    protected void negative(DialogInterface dialog) {
        if(numType == 2){ //小于领货数量，按全部提交，领错了，-1
            status = -1;
            submit();
        }
        dialog.dismiss();
    }

    @Override
    protected void positive(DialogInterface dialog) {
        if(numType == 2){ //小于领货数量，按当前提交，3
            status = 3;
            submit();
        }else if(numType == 1){
            submit();
        }
        dialog.dismiss();
    }

    @Override
    protected void setTimeText(String time) {
        tvTime.setText(time);
    }

    //交货
    private void submit(){
        String time = tvTime.getText().toString();
        String gh = etGh.getText().toString();
        String kh = tvKh.getText().toString();
        String color = tvColor.getText().toString();
        String size = tvSize.getText().toString();
        String num = etNum.getText().toString();
        if(gh.equals("")){
            showToast("请输入工号");
            return;
        }
        if(kh.equals("")){
            showToast("请选择款号");
            return;
        }
        if(color.equals("")){
            showToast("请选择颜色");
            return;
        }
        if(size.equals("")){
            showToast("请选择尺寸");
            return;
        }
        if(num.equals("")){
            showToast("请输入数量");
            return;
        }
        ClothesTable clothes = new ClothesTable();
        clothes.setSubmitDate(time);
        clothes.setWorkerNum(gh);
        clothes.setModelNumber(kh);
        clothes.setColor(color);
        clothes.setSize(size);
        clothes.setUuid(uuid);
        clothes.setStatus(status);
        clothes.setSubmit(parseInt(num));
        String json = new Gson().toJson(clothes);
        put(json,BaseUrl.SUBMIT_CLOTHES);
    }

    @Override
    protected void onSuccess(String res) {
        showToast("交货成功");
        finish();
    }

    //根据款号请求
    private void getDataByKh(String workerNum){
        OkGo.<ServerInfo<List<ClothesTable>>>get(BaseUrl.JH1).params("workerNum",workerNum)
                .execute(new JsonCallBack<ServerInfo<List<ClothesTable>>>() {
                    @Override
                    public void onSuccess(Response<ServerInfo<List<ClothesTable>>> response) {
                        ServerInfo info = response.body();
                        List<ClothesTable> list = (List<ClothesTable>) info.getData();
                        Intent intent = new Intent(SubmitProduct.this,ClaimSelect.class);
                        intent.putExtra("list",(Serializable)list);
                        startActivityForResult(intent,100);
                        isEdit = true;
                    }

                    @Override
                    public void onError(Response<ServerInfo<List<ClothesTable>>> response) {
                        super.onError(response);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data == null) return;
        ClothesTable info = (ClothesTable) data.getSerializableExtra("info");
        uuid = info.getUuid();
        tvKh.setText(info.getModelNumber());
        tvColor.setText(info.getColor());
        tvSize.setText(info.getSize());
        claim = info.getClaimed() - info.getSubmit();
        etNum.setText(claim+"");
    }

    //根据工号请求姓名
    private void getName(String wokerNum){
        OkGo.<String>get(BaseUrl.GetName)
                .params("emplno",wokerNum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String res = response.body().toString();
                        try {
                            JSONObject object = new JSONObject(res);
                            if(object.has("data")){
                                JSONArray array = object.getJSONArray("data");
                                if(array.length()>0){
                                    JSONObject obj = array.getJSONObject(0);
                                    String name = obj.getString("realName");
                                    mTvName.setText(name);
                                }else {
                                    mTvName.setText("");
                                }
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            mTvName.setText("");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        mTvName.setVisibility(View.GONE);
                    }
                });
    }
}
